package com.cpit.qualitycontrol.web.controller;

import com.cpit.platform.common.constant.LogConstant;
import com.cpit.platform.common.entity.Result;
import com.cpit.platform.common.entity.TableDataQueryCondition;
import com.cpit.platform.common.entity.TableJsonData;
import com.cpit.platform.dto.OperLog;
import com.cpit.platform.log.LogOperator;
import com.cpit.platform.service.OperLogService;
import com.cpit.qualitycontrol.common.constant.LogConstantEx;
import com.cpit.qualitycontrol.entity.DeviceType;
import com.cpit.qualitycontrol.service.DeviceTypeService;
import com.cpit.qualitycontrol.service.impl.ServiceUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Date;

/**
 * Created by Hull on 2017/9/28.
 * @author Hull
 * 设备类型Controller类
 */
@RestController
@RequestMapping(value = "/DeviceType")
public class DeviceTypeController {
    private final String loggerName = this.getClass().getName();
    private String logModule = "设备类型：";

    @Autowired
    private DeviceTypeService deviceTypeService = null;

    @Autowired
    private OperLogService operLogService;

    @ApiOperation(value="查询设备类型", notes="通过ID查询设备类型详细信息")
    //@PreAuthorize("hasAuthority('queryDeviceType')")
    @RequestMapping(value="/queryDeviceType/{id}", method = RequestMethod.GET)
    public Result<DeviceType> queryDeviceType(@ApiParam(value = "设备类型ID", required = true) @PathVariable(value = "id") Long id) {
        return new Result<>(Result.CODE_SUCCESS, "", this.deviceTypeService.findById(id));
    }

    @ApiOperation(value="查询所有设备类型", notes="无条件查询设备类型信息，返回对象List")
    //@PreAuthorize("hasAuthority('queryDeviceType')")
    @RequestMapping(value="/queryAllDeviceType", method = RequestMethod.GET)
    public List<DeviceType> queryAllDeviceType() {
        return this.deviceTypeService.findAll();
    }

    @ApiOperation(value="查询设备类型列表", notes="通过条件查询设备类型信息，返回List方式" +
            "支持模糊查询。")
    //@PreAuthorize("hasAuthority('queryDeviceType')")
    @RequestMapping(value="/queryDeviceType", method = RequestMethod.GET)
    public List<DeviceType> queryDeviceType(
            @ApiParam(value = "当前页数， 以1开始。") @RequestParam(value = "page", required = false, defaultValue = "1") int page,
            @ApiParam(value = "当前页的内容长度。") @RequestParam(value = "size", required = false, defaultValue = "20") int size,
            @ApiParam(value = "排序方式：asc为升序，desc为降序。") @RequestParam(value = "order", required = false, defaultValue = "asc") String order,
            @ApiParam(value = "排序字段，与dto中声明的字段名称一致。") @RequestParam(value = "orderBy", required = false, defaultValue = "id") String orderBy,
            @ApiParam(value = "模糊搜索的字符串，根据角色的名称字段进行模糊匹配。") @RequestParam(value = "pattern", required = false, defaultValue = "") String pattern) {
        return this.deviceTypeService.findByCondition(page, size, order, orderBy, pattern);
    }

    @ApiOperation(value="分页查询设备类型", notes="通过条件查询设备类型信息，返回jqGrid分页JSON形式，支持模糊查询。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cond", value = "JqGrid的条件对象，由JqGrid根据js参数自动封装。", required = true, dataType = "TableDataQueryCondition")
    })
    @SuppressWarnings("rawtypes")
    //@PreAuthorize("hasAuthority('queryDeviceType')")
    @RequestMapping(value="/queryDeviceTypeJqg", method = RequestMethod.GET)
    public TableJsonData queryDeviceTypeJqg(TableDataQueryCondition cond) {
        return this.deviceTypeService.findByConditionJqg(cond);
    }

    @ApiOperation(value="创建设备类型", notes="用户手工指定设备类型并创建，" +
            "需要手动输入设备类型名称和描述信息，设备类型名称不能重复。")
    @ApiImplicitParam(name = "data", value = "设备类型对象", required = true, dataType = "DeviceType")
    //@PreAuthorize("hasAuthority('createDeviceType')")
    @RequestMapping(value="/createDeviceType", method = RequestMethod.POST)
    public Result<DeviceType> createDeviceType(@RequestBody DeviceType data) {
        try{
            DeviceType retDeviceType = this.deviceTypeService.create(data);
            writeLog(LogConstant.OPER_CREATE,Result.CODE_SUCCESS,logModule+retDeviceType.getName());
            return new Result<>(Result.CODE_SUCCESS, "", retDeviceType);
        } catch(Exception e) {
            LogOperator.err(loggerName, "createDeviceType error:" + data, e);
            writeLog(LogConstant.OPER_CREATE,Result.CODE_FAILED,logModule + e.getMessage());
            return new Result<>(Result.CODE_FAILED, e.getMessage(), data);
        }
    }

    @ApiOperation(value="修改设备类型", notes="用户手工指定设备类型并修改，" +
            "需要手动输入设备类型名称和描述信息，设备类型名称不能重复。")
    @ApiImplicitParam(name = "data", value = "设备类型对象", required = true, dataType = "DeviceType")
    //@PreAuthorize("hasAuthority('modifyDeviceType')")
    @RequestMapping(value="/modifyDeviceType", method = RequestMethod.POST)
    public Result<DeviceType> modifyDeviceType(@RequestBody DeviceType data) {
        try{
            DeviceType retDeviceType = this.deviceTypeService.modify(data);
            writeLog(LogConstant.OPER_MODIFY,Result.CODE_SUCCESS,logModule + data.getName());
            return new Result<>(Result.CODE_SUCCESS, "", retDeviceType);
        } catch(Exception e) {
            LogOperator.err(loggerName, "modifyDeviceType error:" + data, e);
            writeLog(LogConstant.OPER_CREATE,Result.CODE_FAILED,logModule + e.getMessage());
            return new Result<>(Result.CODE_FAILED, e.getMessage(), data);
        }
    }

    @ApiOperation(value="删除设备类型", notes="在系统中删除指定设备类型")
    @ApiImplicitParam(name = "data", value = "设备类型对象", required = true, dataType = "DeviceType")
    //@PreAuthorize("hasAuthority('deleteDeviceType')")
    @RequestMapping(value="/deleteDeviceType", method = RequestMethod.DELETE)
    public Result<DeviceType> deleteDeviceType(@RequestBody DeviceType data) {
        try{
            this.deviceTypeService.delete(data);
            writeLog(LogConstant.OPER_DELETE,Result.CODE_SUCCESS,logModule + data.getName());
            return new Result<>(Result.CODE_SUCCESS, "", data);
        } catch(Exception e) {
            LogOperator.err(loggerName, "deleteDeviceType error:" + data, e);
            writeLog(LogConstant.OPER_CREATE,Result.CODE_FAILED,logModule + e.getMessage());
            return new Result<>(Result.CODE_FAILED, e.getMessage(), data);
        }
    }

    @ApiOperation(value="删除设备类型", notes="在系统中删除指定设备类型")
    //@PreAuthorize("hasAuthority('deleteDeviceType')")
    @RequestMapping(value="/deleteDeviceType/{id}", method = RequestMethod.DELETE)
    public Result<DeviceType> deleteDeviceType(@ApiParam(value = "设备类型ID", required = true) @PathVariable("id") Long id) {
        try{
            this.deviceTypeService.delete(id);
            writeLog(LogConstant.OPER_DELETE,Result.CODE_SUCCESS,logModule + deviceTypeService.findById(id).getName());
            return new Result<>(Result.CODE_SUCCESS, id.toString());
        } catch(Exception e) {
            LogOperator.err(loggerName, "deleteDeviceType error:id=" + id, e);
            writeLog(LogConstant.OPER_CREATE,Result.CODE_FAILED,logModule + e.getMessage());
            return new Result<>(Result.CODE_FAILED, e.getMessage());
        }
    }

    /**
     *
     * @param result
     * @param detail
     */
    private  void  writeLog(String op,String result, String detail){
        OperLog operLog =new OperLog();
        operLog.setOperateTime(new Date());
        operLog.setModule(LogConstantEx.MODULE_SYSTEM);
        operLog.setCommand(op);
        operLog.setResult(result);
        operLog.setOperateUser(ServiceUtils.getLoginUser().getUsername());
        operLog.setDetail(detail);
        operLogService.writeLog(operLog);
    }
}
